var allBase = null;
var stackGuid = null;
var allpoint = null;
var allCSchedule = null;
var all_CSReports = null;//进度详情
var pguid = null;
var userall = null;
$(function () {
    $.when(
        getuserall(),
        $.get(baseURL+"csg/cpbase/select?ourid=isok",function (r) {
            allBase = r.returnlist;
            vm.allBase = allBase;
        }),
        $.get(baseURL+"csg/cschedule/select",function (r) {
            allpoint = r.returnlist;
            vm.allpoint = allpoint;
        }),
        $.get(baseURL+"csg/cschedulereport/selectToUpdatetime",function (r) {
            all_CSReports = r.returnlist;
            vm.all_CSReports = all_CSReports;
        })
    ).done(

        $("#jqGrid1").jqGrid({
            url: baseURL +'csg/cpbase/list?state=isdelno&ourid=isok',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden: true  },

                { label: '项目名称', name: 'pBName', index: 'p_b_name', width: 200 },
                { label: '参与人', name: 'pBCollectid', index: 'p_b_collectid', width: 150 ,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";


                        var ss = (cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "") + "").split(",");
                        for (var i = 0; i < ss.length; i++) {

                            for (d in userall) {
                                if (ss[i] == userall[d].userId + "") {

                                    names += userall[d].username + ",";
                                }
                            }
                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },

                { label: '创建时间', name: 'pBAddtime', index: 'p_b_addtime', width: 150,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd hh:mm'):"";}
                }
            ],
            viewrecords: true,
            height: 500,

            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager1",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid1").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        }),

        $("#jqGrid").jqGrid({
            //后台已有限制条件
            url: baseURL + 'csg/cschedule/list',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
                { label: '项目名称', name: 'pGuid', index: 'p_guid', width: 80,hidden:true,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in allBase) {
                            if (cellvalue == allBase[d].guid)
                                return allBase[d].pBName;

                        }
                    }
                },
                { label: '所属项目名称', name: 'pName', index: 'p_name', width: 80,hidden:true },
                // { label: '最新图片', name: 'sPicture', index: 's_picture', width: 80,align: "center",hidden:true,
                //     sortable: false, editable: false,formatter: alarmFormatter
                // },
                { label: '进度名称', name: 'sName', index: 's_name', width: 80 },
                { label: '进度排序', name: 'sSort', index: 's_sort', width: 80,hidden:true },
                { label: '最新记录', name: 'guid', index: 'guid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        var ss;
                        var aa = " ";
                        if (all_CSReports.length == 0){
                            return aa;
                        }
                        for (var d in all_CSReports) {
                            ss=" ";
                            if (cellvalue == all_CSReports[d].sGuid){
                                ss= all_CSReports[d].sRDetails;
                                break;
                            }
                        }
                        return ss;
                    }
                },
                { label: '记录时间', name: 'guid', index: 'guid', width: 80,
                    /*formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd'):"";
                    }*/
                    formatter: function (cellvalue, options, rowObject) {
                        var tt;
                        var aa = " ";
                        if (all_CSReports.length == 0){
                            return aa;
                        }

                        for (var d in all_CSReports) {
                            tt = " ";
                            if (cellvalue == all_CSReports[d].sGuid){
                                tt = cellvalue!=null?new Date(all_CSReports[d].sRAddtime).Format('yyyy-MM-dd'):"";
                                break;
                            }

                        }
                        return tt;
                    }
                },
                { label: '倒排工期', name: 'inverTime', index: 'inverTime', width: 80,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd'):"";
                    }
                },
                { label: '是否控制节点', name: 'controlPoint', index: 'controlPoint', width: 80 },
                { label: '状态', name: 'sDatastate', index: 's_datastate', width: 80,hidden:true },
                { label: '操作', name: '', width: 100,
                    formatter: function (cellvalue, options, rowObject) {
                        return "<a  class='btn btn-primary' onclick='showInformation(\"" + rowObject.guid + "\")' >&nbsp;进度填报</a>"
                        // +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exports(\"" + rowObject.guid + "\")' >&nbsp;进度导出</a>"
                        // +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportsimg(\"" + rowObject.guid + "\")' >&nbsp;导出进度照片</a>"
                    }
                }
            ],
            viewrecords: true,
            height: 385,
            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        })
    )
});


/**
 *  填报信息
 * @param guid
 */
function showInformation(guid) {
    var title ="填报信息";
    var pGuid = vm.p.pGuid;
    var content = "csmiddlechedule.html?sGuid=" + guid+"&pGuid="+pGuid;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['95%', '95%'],
        content: content

    });
}
function  getuserall()
{
    $.get(baseURL + "sys/user/select" , function (r) {
        userall = r.returnlist;

    });
    vm.userall=userall;

}

function alarmFormatter(cellvalue, options, rowdata) {
    return ' <img  src="' +baseURL+'rest/photo/queryPic?address='+ cellvalue + '"  id="img' + rowdata.guid + '"  style="width:40px;height:40px;" />';
}
function imgShow(outerdiv, innerdiv, bigimg, _this){
    var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
    $(bigimg).attr("src", src);//设置#bigimg元素的src属性

	/*获取当前点击图片的真实大小，并显示弹出层及大图*/
    $("<img/>").attr("src", src).load(function(){
        var windowW = $(window).width();//获取当前窗口宽度
        var windowH = $(window).height();//获取当前窗口高度
        var realWidth = this.width;//获取图片真实宽度
        var realHeight = this.height;//获取图片真实高度
        var imgWidth, imgHeight;
        var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放

        if(realHeight>windowH*scale) {//判断图片高度
            imgHeight = windowH*scale;//如大于窗口高度，图片高度进行缩放
            imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
            if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
                imgWidth = windowW*scale;//再对宽度进行缩放
            }
        } else if(realWidth>windowW*scale) {//如图片高度合适，判断图片宽度
            imgWidth = windowW*scale;//如大于窗口宽度，图片宽度进行缩放
            imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
        } else {//如果图片真实高度和宽度都符合要求，高宽不变
            imgWidth = realWidth;
            imgHeight = realHeight;
        }
        $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放

        var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
        var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
        $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
        $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
    });

    $(outerdiv).click(function(){//再次点击淡出消失弹出层
        $(this).fadeOut("fast");
    });
}

/**
 * 导出进度详情
 */
function exportCSedule() {
    var pGuid = vm.p.pGuid;
    if (pGuid == null){
        alert("请选择项目");
        return;
    }
    location.href=baseURL + "csg/cschedule/exports?pGuid="+pGuid;
}

/**
 *  导出照片
 */
function exportCSeduleIms() {
    var pGuid = vm.p.pGuid;
    if (pGuid == null){
        alert("请选择项目");
        return;
    }
    location.href=baseURL + "csg/cschedule/exportsimg?pGuid="+pGuid;
}


/**
 *  项目进度
 */
function getProject() {
    //获取所选项目的guid
    stackGuid = $("#projectIdquer").val();

    //根据项目ID获取所属项目下的项目进度
    var url = baseURL+'csg/cschedule/select?pGuid='+stackGuid;

    $.get(url, function (data) {
        var allCStackPoint = data.returnlist;
        var str="";
        for(var i=0;i<allCStackPoint.length;i++)
        {
            str+="<li value='" + allCStackPoint[i]['guid'] + "' onmouseover='getCSchedule()'>"+allCStackPoint[i]['sName']+"</li>";
        }
        $('#J_List').html(str);
    }, "json");

}

/**
 *  tree-项目进度
 */
function getCSchedule() {
    var obj_lis = document.getElementById("J_List").getElementsByTagName("li");

    var sName ;
    var sGuid ;
    for(i=0;i<obj_lis.length;i++){

        obj_lis[i].onclick = function(){

            sName = this.innerHTML;

            sGuid = $(this).attr("value"); //获取每个li的value值

            showInformation(sGuid);
        }
    }

}


var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        userall:userall,
        p:{
            psname:null,
            ppppBName:null,
            pGuid:null
        },
        allBase:allBase,
        allpoint:allpoint,
        all_CSReports:all_CSReports,
        allCSchedule:allCSchedule,
        cSchedule: {}
    },
    methods: {
        query: function () {
            vm.reload();
        },
        qu: function () {
            $('ul').on('click','li',function () {
                alert("请选择项目")
            });
            alert("请选择项目名称");
        },

        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.cSchedule = {};
        },
        update: function (event) {
            var guid = getSelectedRow();
            if(guid == null){
                return ;
            }

            var rowData = $("#jqGrid").jqGrid('getRowData',guid);
            var pname = rowData.pGuid;
            $.get(baseURL + "csg/cpbase/select?pname="+pname, function(r) {
                pguid=r.returnlist[0].guid;

                $.get(baseURL + "csg/cpbase/info/"+pguid, function(r) {
                    if (r.cPBase.pBState == 30) {
                        alert("项目已归档，无法修改进度信息！");
                    }else{

                        vm.showList = false;
                        vm.title = "修改";

                        vm.getInfo(guid)
                    }
                });

            });

        },
        saveOrUpdate: function (event) {
            var pGuid = vm.p.pGuid;
            var url = vm.cSchedule.guid == null ? "csg/cschedule/saveNew/"+pGuid : "csg/cschedule/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.cSchedule),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                            console.log("cschedu===刷新成功！")
                            // location.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var guids = getSelectedRows();
            if(guids == null){
                return ;
            }
            var guid=guids[0];
            var rowData = $("#jqGrid").jqGrid('getRowData',guid);
            var pguid = rowData.pGuid;
            // $.get(baseURL + "csg/cpbase/select?pname="+pname, function(r) {
            //     pguid=r.returnlist[0].guid;

            $.get(baseURL + "csg/cpbase/info/"+pguid, function(r) {
                if (r.cPBase.pBState != 30) {
                    confirm('确定要删除选中的记录？', function(){
                        $.ajax({
                            type: "POST",
                            url: baseURL + "csg/cschedule/delete",
                            contentType: "application/json",
                            data: JSON.stringify(guids),
                            success: function(r){
                                if(r.code == 0){
                                    alert('操作成功', function(index){
                                        $("#jqGrid").trigger("reloadGrid");
                                    });
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    });
                }else{
                    alert("项目已归档，无法删除记录信息！")
                }
            })

        },
        getInfo: function(guid){
            $.get(baseURL + "csg/cschedule/info/"+guid, function(r){
                vm.cSchedule = r.cSchedule;
                vm.cSchedule.sTime = r.cSchedule.sTime !=null? new Date().Format("yyyy-MM-dd"):"";
                vm.cSchedule.inverTime = r.cSchedule.inverTime !=null? new Date().Format("yyyy-MM-dd"):"";


            });
        },
        showprolist:function (event) {

            // vm.q.pGuid='b6400318-7a6f-4de5-92e8-ddec55f10394';
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择项目",
                area: ['700px', '460px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayermy"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGrid1");
                    var rowKey = grid.getGridParam("selrow");
                    if (!rowKey) {
                        alert("请选择一条记录");
                        return;
                    }

                    var selectedIDs = grid.getGridParam("selarrrow");
                    if (selectedIDs.length > 1) {
                        alert("只能选择一条记录");
                        return;
                    }
                    // vm.getBasic(selectedIDs[0]);
                    vm.p.pGuid=selectedIDs[0];

                    for (d in  allBase) {
                        if (allBase[d].guid == selectedIDs[0]) {
                            vm.p.psname=allBase[d].pBName;
                        }
                    }
                    layer.close(index);

                }
            });


        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    // 'pName':vm.p.pName,
                    // 'sName':vm.p.sName,
                    // 'inverTime':vm.p.inverTime
                    'pGuid':vm.p.pGuid
                },
                page:page
            }).trigger("reloadGrid");


            // $.get(baseURL+"csg/cschedulereport/selectToUpdatetime?pGuid="+vm.p.pGuid,function (r) {
            //     all_CSReports = r.returnlist;
            //     vm.all_CSReports = all_CSReports;
            // })
        },
        reloadpro: function (event) {

            console.log("a_______");
            var page = $("#jqGrid1").jqGrid('getGridParam','page');
            $("#jqGrid1").jqGrid('setGridParam',{
                postData:{
                    'pBName': vm.p.ppppBName,
                },
                page:page
            }).trigger("reloadGrid");
        }
    }
});